package com.wss.common.view.browser;

import com.wss.common.base.BaseMvpAbility;
import com.wss.common.base.ResourceTable;
import com.wss.common.constants.Constants;
import com.wss.common.constants.Dic;
import com.wss.common.utils.AnimatorValueUtils;
import com.wss.common.utils.NetworkUtil;
import com.wss.common.utils.ValidUtils;
import com.wss.common.view.browser.mvp.BrowserPresenter;
import com.wss.common.view.browser.mvp.contract.BrowserContract;
import com.wss.common.widget.dialog.AppDialog;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.*;
import ohos.agp.components.webengine.ResourceRequest;
import ohos.agp.components.webengine.WebAgent;
import ohos.agp.components.webengine.WebConfig;
import ohos.agp.components.webengine.WebView;
import ohos.multimodalinput.event.KeyEvent;

public class BrowserAbility extends BaseMvpAbility<BrowserPresenter>
        implements BrowserContract.View, Component.ClickedListener {

    private Text tvTitle;
    private ProgressBar progressBar;
    private WebView webView;
    private DependentLayout webViewLayout;
    private Image ivEmpty;
    private Text tvEmpty;
    private DirectionalLayout llEmptyView;
    private Image ivBack;
    private Text tvBack;
    private Text tvCloseRight;
    private DependentLayout relHeader;
    /**
     * 本地缓存目录
     */
    private String appCacheDir = Constants.WebView.CACHE_DIR;
    private boolean isFullScreen = false;
    private String url;
    private String title;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        initView();
    }

    @Override
    protected BrowserPresenter createPresenter() {
        return new BrowserPresenter();
    }

    @Override
    protected int getLayoutId() {
        return ResourceTable.Layout_ability_browser;
    }

    public void hiddenHeader() {
        relHeader.setVisibility(Component.HIDE);
    }

    protected void initView() {
        findView();
        initListener();

//        setImmersionBarColor(ResourceTable.Color_white);
        url = getIntent().getStringParam(Dic.URL);
        title = getIntent().getStringParam(Dic.TITLE_TEXT);
        tvCloseRight.setVisibility(Component.HIDE);
        tvBack.setVisibility(Component.HIDE);
        tvTitle.setText(title);
        initWebView();
        refreshPage();
    }

    private void findView() {
        tvTitle = (Text) findComponentById(ResourceTable.Id_tv_title);
        progressBar = (ProgressBar) findComponentById(ResourceTable.Id_progress_bar);
        webView = (WebView) findComponentById(ResourceTable.Id_web_view);
        ivEmpty = (Image) findComponentById(ResourceTable.Id_iv_empty);
        tvEmpty = (Text) findComponentById(ResourceTable.Id_tv_empty);
        llEmptyView = (DirectionalLayout) findComponentById(ResourceTable.Id_ll_empty_view);
        ivBack = (Image) findComponentById(ResourceTable.Id_img_back);
        tvBack = (Text) findComponentById(ResourceTable.Id_tv_back);
        tvCloseRight = (Text) findComponentById(ResourceTable.Id_tv_close_right);
        relHeader = (DependentLayout) findComponentById(ResourceTable.Id_rl_browser_header);
        webViewLayout = (DependentLayout) findComponentById(ResourceTable.Id_rl_webview_view);
    }

    private void initListener() {
        ivBack.setClickedListener(this::onClick);
        tvBack.setClickedListener(this::onClick);
        tvCloseRight.setClickedListener(this::onClick);
    }

    @Override
    public void onClick(Component component) {
        int id = component.getId();
        if (id == ResourceTable.Id_img_back||id == ResourceTable.Id_tv_back) {
            goBack();
        } else if (id == ResourceTable.Id_tv_close_right) {
            terminateAbility();
        }
    }

    /**
     * 获取一个WebView实例
     *
     * @return
     */
    public WebView getWebView() {
        return webView;
    }

    private void initWebView() {
        WebConfig webConfig = webView.getWebConfig();
        webConfig.setJavaScriptPermit(true);
        webConfig.setWebStoragePermit(true);
        webConfig.setLocationPermit(true);
        webConfig.setTextAutoSizing(true);
        webConfig.setViewPortFitScreen(false);
        webConfig.setDataAbilityPermit(true);

//        webView.setWebAgent(new WebAgent() {
//            @Override
//            public boolean isNeedLoadUrl(WebView webView, ResourceRequest request) {
//                if (request == null || request.getRequestUrl() == null) {
////                    LogUtil.info(TAG,"WebAgent isNeedLoadUrl:request is null.");
//                    return false;
//                }
//                String url = request.getRequestUrl().toString();
//                if (url.startsWith("http:") || url.startsWith("https:")) {
//                    webView.load(url);
//                    return false;
//                } else {
//                    webView.load(url);
//                    return super.isNeedLoadUrl(webView, request);
//                }
//            }
//        });
    }

    private class JavaScriptApi {

    }

    /**
     * WebView调用JS
     *
     * @param method 方法名
     * @param data   参数多参已逗号分隔
     */
    private void loadJsMethod(String method, String data) {
        if (ValidUtils.isValid(data)) {
            //传递参数调用
            String format = String.format("javascript:%s('%s')", method, data);
            webView.load(format);
        } else {
            // 无参数调用
            webView.load(String.format("javascript:%s()", method));
        }
    }

    /**
     * 刷新页面 显示网页
     */
    private void refreshPage() {
        if (NetworkUtil.isNetworkEnabled(context)) {
            webView.setVisibility(Component.VISIBLE);
            progressBar.setVisibility(Component.VISIBLE);
            webView.load(url);
        } else {
            showErrorPage(true);
        }
    }

    /**
     * 显示进度条
     */
    private void showProgressView() {
        AnimatorValue anim = new AnimatorValue();
        anim.setDuration(200);
        progressBar.setVisibility(Component.VISIBLE);
        anim.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                float animatedValue = AnimatorValueUtils.getAnimatedValue(v, 0, 1);
                progressBar.setAlpha(animatedValue);
            }
        });
        anim.start();
    }

    /**
     * 隐藏进度条
     */
    protected void dismissProgressView() {
        AnimatorValue anim = new AnimatorValue();
        anim.setDuration(200);
        progressBar.setVisibility(Component.VISIBLE);
        anim.setValueUpdateListener(new AnimatorValue.ValueUpdateListener() {
            @Override
            public void onUpdate(AnimatorValue animatorValue, float v) {
                float animatedValue = AnimatorValueUtils.getAnimatedValue(v, 1, 0);
                progressBar.setAlpha(animatedValue);
            }
        });
        anim.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {

            }

            @Override
            public void onStop(Animator animator) {

            }

            @Override
            public void onCancel(Animator animator) {

            }

            @Override
            public void onEnd(Animator animator) {
                progressBar.setVisibility(Component.HIDE);
            }

            @Override
            public void onPause(Animator animator) {

            }

            @Override
            public void onResume(Animator animator) {

            }
        });
        anim.start();
    }

    /**
     * 显示错误页面
     *
     * @param showError 显示
     */
    private void showErrorPage(boolean showError) {
        if (showError) {
            llEmptyView.setVisibility(Component.VISIBLE);
            webViewLayout.setVisibility(Component.HIDE);
        } else {
            llEmptyView.setVisibility(Component.HIDE);
            webViewLayout.setVisibility(Component.VISIBLE);
        }
    }

    /**
     * TODO 设置WebView缓存容量
     *
     */
    public void setPageCacheCapacity() {

    }

    /**
     * 弹出对话框
     *
     * @param message 提示信息
     */
    private void showDialog(String message) {
        new AppDialog.Builder(context)
                .setContent(message)
                .create()
                .show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            goBack();
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

    /**
     * TODO 返回上一步
     */
    private void goBack() {
        terminateAbility();
    }
}
